<template>
  <app-container>
    <app-block>
      <zm-form :model="searchForm" ref="searchForm" inline>
        <zm-form-item prop="name">
          <zm-input
            class="w200"
            v-model="searchForm.name"
            :placeholder="`请输入${isDraft?'产品名称':'产品名称/编码'}搜索`"
          />
        </zm-form-item>
        <zm-form-item v-if="isDraft" prop="code">
          <zm-input
            class="w200"
            v-model="searchForm.code"
            placeholder="请输入产品编码查询"
          />
        </zm-form-item>
        <zm-form-item prop="businessTypeName" v-if="isShowSearch">
          <zm-data-select
            v-model="searchForm.businessTypeName"
            :list="BUSINESS_TOTAL_TYPE"
            class="w200"
            @change="handleChangeType"
            placeholder="请选择业务类型"
            str
          >
          </zm-data-select>

          <zm-data-select
            v-model="searchForm.businessType"
            :list="businessTypeList"
            class="w200"
            clearable
            placeholder="请选择"
            multiple
            str
          >
          </zm-data-select>
        </zm-form-item>
        <zm-form-item prop="productType" v-if="isShowSearch">
          <zm-data-select
            v-model="searchForm.productType"
            k1="productType"
            class="w200"
            clearable
            placeholder="产品类型"
            multiple
            str
          >
          </zm-data-select>
        </zm-form-item>
        <zm-form-item prop="exchangeRange" v-if="isShowSearch">
          <zm-data-select
            v-model="searchForm.exchangeRange"
            :list="PRODUCT_EXCHANGE"
            class="w200"
            clearable
            placeholder="兑换范围"
            multiple
            str
          >
          </zm-data-select>
        </zm-form-item>
        <zm-form-item prop="apartmentId" v-if="isShowSearch">
          <tree-select
            ref="treeSelect"
            v-model="searchForm.apartmentId"
            :tree="apartmentList"
            :tree-props="{ label: 'name', valueKey: 'value' }"
            :is-checkbox="true"
            placeholder="可售部门"
            class="dib"
          ></tree-select>
        </zm-form-item>
        <zm-form-item label prop="salesType">
        <!-- <el-tooltip class="item" effect="dark" :content="getSalesOrderTypeName" :disabled="!searchForm.salesType" placement="top-start"> -->
          <zm-data-select
            v-model="searchForm.salesType"
            :list="saleOrderTypeList"
            placeholder="销售单类型"
            multiple
            str
            class="w200"
          ></zm-data-select>
        <!-- </el-tooltip> -->
        </zm-form-item>
        <zm-form-item>
          <zm-button @click="onSearch" t="search"></zm-button>
          <zm-button @click="handleReset" t="reset"></zm-button>
        </zm-form-item>
        <zm-form-item label="审批状态：" class="db" id="productConfigRadioNone">
          <zm-data-radio
            is-btn
            :list="CHECK_TYPE"
            v-model="searchForm.checkStatus"
            @change="onReset"
          />
        </zm-form-item>
      </zm-form>
    </app-block>
    <app-block>
      <zm-button
        type="primary"
        icon="el-icon-plus"
        @click="onEdit({})"
        t="add"
        class="mb10"
      >
      </zm-button>
      <zm-button
        v-if="searchForm.checkStatus === '3'"
        type="warning"
        icon="el-icon-setting"
        @click="handleSetSale"
        class="mb10"
        :disabled="tableParams.selectList.length === 0"
      >
        设为可售
      </zm-button>
      <zm-table-data
        :data="tableParams.data"
        :columns="columns"
        :fetch="loadList"
        :table-params="tableParams"
        :show-page="true"
        :mutilple="isShowMutilple"
        pk="id"
        @selection-change="getSelectionIds"
        heigth="100px"
        ref="zmTableData"
      >
      </zm-table-data>
    </app-block>
    <!-- 配置产品 -->
    <new-product
      v-if="newProductParams.visible"
      v-model="newProductParams.visible"
      :id="newProductParams.id"
      @re-load="loadList"
    />
    <!-- 产品详情 -->
    <detail
      v-if="detailParams.visible"
      v-model="detailParams.visible"
      :id="detailParams.id"
      @after-save="loadList"
      :is-show-btn="false"
    />
  </app-container>
</template>

<script>
import { columns, PRODUCT_EXCHANGE, BUSINESS_TOTAL_TYPE } from './const'
import tableMixin from '@/mixins/zmTableMixin'
import productDraftApis from '@/api/src/productDraft'
import publicApis from '@/api/src/public'
import draftApis from '@/api/src/draft'
import NewProduct from './components/NewProduct'
import Detail from '@/components/DetailContainer'
import { CHECK_TYPE, BUSINESS_TYPE, PROCESS_TYPE } from '@/model'
import approveApis from '@/api/src/approve'
import TreeSelect from '@/components/TreeSelect'
import {getBusinessType} from '@/api/src/productDraft.js'
export default {
  // 产品配置
  name: 'ProductConfig',
  components: { NewProduct, Detail, TreeSelect },
  mixins: [tableMixin],
  data () {
    return {
      CHECK_TYPE,
      BUSINESS_TYPE,
      PRODUCT_EXCHANGE,
      PROCESS_TYPE,
      BUSINESS_TOTAL_TYPE,
      businessTypeList: [],
      searchForm: {
        code: '',
        businessTypeName: '',
        name: '', // 产品名称
        businessType: '', // 业务类型
        productType: '', // 业务类型
        exchangeRange: '', // 兑换范围
        apartmentId: '', // 部门id
        checkStatus: '3', // 审批状态
        salesType: '' // 销售单类型
      },
      newProductParams: {
        visible: false
      },
      detailParams: {
        visible: false
      },
      apartmentList: [],
      productTypeList: []
    }
  },
  computed: {
    columns () {
      return columns(this)
    },
    isShowMutilple () {
      return this.searchForm.checkStatus === '3'
    },
    // 是否展示搜索框
    isShowSearch () {
      return ['3', '0'].includes(this.searchForm.checkStatus)
    },
    isDraft () {
      return ['2', '1', '4'].includes(this.searchForm.checkStatus)
    },
    saleOrderTypeList () {
      return this.$auth.getBaseDataByType('saleOrderType').filter(item => {
        return ['1', '2', '3', '4', '5'].includes(item.value)
      })
    },
    getSalesOrderTypeName () {
      let _nameArr = []
      this.saleOrderTypeList.forEach(item => {
        if (this.searchForm.salesType.indexOf(item.value) > -1) {
          _nameArr.push(item.name)
        }
      })
      return _nameArr.join(',')
    }
  },
  watch: {},
  created () {
    this.init()
  },
  methods: {
    async init () {
      this.apartmentList = await publicApis.apartmentList()
      // this.getBusinessTypeList()
    },
    async loadList () {
      let _res
      // 被驳回、审批中、已撤销请求接口 产品：1，特殊方案关联产品：2，特殊方案关联销售单：3
      if (this.isDraft) {
        _res = await draftApis.getPageList(this.assignQuery({...this.searchForm, type: '1'}))
      } else {
        // 已通过、未提交请求接口
        _res = await productDraftApis.getPageList(
          this.assignQuery({...this.searchForm, isNotProduct: '1'})
          // isNotProduct // 屏蔽实物产品数据
        )
      }
      this.initialTableData(_res.list, _res.count)
    },
    // 批量设为可售
    handleSetSale () {
      const _res = this.getSelectionIds()
      const _count = this.tableParams.selectList.length
      this.$confirm(`已选 ${_count} 条数据，确定全部设为可售状态？`, '批量操作')
        .then(async () => {
          const res = await productDraftApis.onSale({ ids: _res.join(',') })
          this.$refs.zmTableData.clearSelection()
          this.loadList()
          this.$message.success(res.content)
        })
        .catch((err) => err)
    },
    // 新增/编辑
    onEdit (row) {
      this.newProductParams = {
        visible: true,
        id: this.isDraft ? row.relationId : row.id
      }
    },
    onDetail (row) {
      this.detailParams = {
        visible: true,
        id: this.isDraft ? row.relationId : row.id
      }
    },
    async onSubmit (row) {
      if (!this.isDraft && +row.isComplete === 0) {
        this.$message.warning('信息未填写完整，请完善信息后再提交审批')
        return
      }
      const ID = this.isDraft ? row.relationId : row.id
      await approveApis.checkApprove({processType: PROCESS_TYPE.product})
      await approveApis.submit({
        processType: PROCESS_TYPE.product,
        linkName: row.name,
        businessId: ID
      })
      this.onSearch()
      this.$message.success('操作成功')
    },
    async onBack (row) {
      const ID = this.isDraft ? row.relationId : row.id
      await approveApis.cancel({
        processType: PROCESS_TYPE.product,
        businessId: ID,
        linkName: row.name
      })
      this.onSearch()
      this.$message.success('操作成功')
    },
    async onCopy (row) {
      this.$confirm('确定复制？', '复制', {
        type: 'warning'
      }).then(async () => {
        const ID = this.isDraft ? row.relationId : row.id
        await productDraftApis.copy({ id: ID })
        this.$set(this.searchForm, 'checkStatus', '0')
        this.loadList()
        this.$message.success('复制成功')
      })
    },
    onSet (row) {
      let text = '是否设为可售？'
      this.$confirm(text, '设为可售', { type: 'warning' })
        .then(async () => {
          await productDraftApis.onSale({ ids: row.id })
          this.loadList()
          this.$message.success('已成功设为可售产品')
        })
        .catch((err) => err)
    },
    async onDel (row) {
      this.$confirm('确定删除？将不可恢复，请谨慎操作', '删除', {
        type: 'warning'
      })
        .then(async () => {
          // 审批中的数据不能删除
          if (+row.checkStatus === 1) {
            this.$message.warning('该产品已进入审批流程，无法删除！')
          } else {
            const ID = this.isDraft ? row.relationId : row.id
            await productDraftApis.delete({ ids: ID })
            // this.isDraft ? await draftApis.delete({id: ID}) : await productDraftApis.delete({ ids: ID })
            this.onSearch()
            this.$message.success('操作成功')
          }
        })
        .catch((err) => err)
    },
    handleReset () {
      this.searchForm.businessType = ''
      this.businessTypeList = []
      this.$refs.treeSelect && this.$refs.treeSelect.clearSelect()
      this.onReset()
    },

    async getBusinessTypeList () {
      try {
        const _res = await getBusinessType({type: this.searchForm.businessTypeName})
        this.businessTypeList = _res.data
        this.searchForm.businessType = ''
      } catch (error) {
        this.businessTypeList = []
      }
    },
    handleChangeType () {
      if (this.searchForm.businessTypeName) {
        this.getBusinessTypeList()
      } else {
        this.searchForm.businessType = ''
        this.businessTypeList = []
      }
    }
  }
}
</script>
